package com.qst.survey.handler;

import com.qst.survey.util.JwtUtil;
import com.qst.survey.util.NoAuthorization;
import com.qst.survey.util.RedisUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 *
 * @author 10442
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    RedisUtils redisUtils;

    /**
     * @param request      ：请求类
     * @param response：回复类
     * @param handler      ：对象
     * @return boolean
     * @description TODO   执行之前进行拦截,判断token有效性
     * @date 2021/4/2
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入拦截器");


        //判断是否包含了注解,那就不需要做处理
        if ((handler instanceof HandlerMethod)) {
            System.out.println("进入获取注解");
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            NoAuthorization annotation = handlerMethod.getMethod().getAnnotation(NoAuthorization.class);
            if (annotation != null) {
                return true;
            }
        }
        //获取请求头的token
        String token = request.getHeader("authorization");
        System.out.println("请求头token:" + token);
        //如果未获取到token就返回错误请求头
        if (token == null || "".equals(token)) {
            response.setStatus(401);
            return false;
        }
        Claims body = null;
        try {
            body = JwtUtil.getBody(token);
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
        String ip = request.getRemoteAddr();
        String username = body.getId();
        System.out.println("ip" + ip);
        String token1 = null;
        //查询数据库有没有token未登录
        try {
            token1 = redisUtils.getToken(username);
            redisUtils.addTime(username);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        if (token1 == null) {
            response.setStatus(401);
            return false;
        }
        //ip不一样就提示ip冲突
        if (!ip.equals(body.getSubject())) {
            response.setStatus(409);
            return false;
        }
        return true;
    }
}
